import random
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest

import redis
from server.setting import Config

# 阿里云短信服务配置
access_key_id = 'LTAI5tR6ujADH6p4MHQfsgVa'
access_key_secret = 'nbwJUcjmsHB1anFDV8kKsOBVVglFMk'
sign_name = '北海市融媒体中心'
template_code = 'SMS_482880531'

redis_host = Config.REDIS_HOST
redis_port = Config.REDIS_PORT
redis_password = Config.REDIS_PASSWORD


# 生成随机验证码
def generate_random_code():
    return str(random.randint(100000, 999999))


# 发送短信验证码
def send_sms_code(phone_number):
    client = AcsClient(access_key_id, access_key_secret, 'cn-hangzhou')
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protocol_type('https')  # https | http
    request.set_version('2017-05-25')
    request.set_action_name('SendSms')

    code = generate_random_code()

    r = redis.Redis(host=redis_host, port=redis_port, password=redis_password, db=Config.REDIS_DB)
    r.setex(phone_number, 900, code)  # 设置过期时间为15分钟（900秒）

    params = {
        'RegionId': "cn-hangzhou",
        'PhoneNumbers': phone_number,
        'SignName': sign_name,
        'TemplateCode': template_code,
        'TemplateParam': "{\"code\":\"" + code + "\"}"
    }
    request.add_query_param('RegionId', params['RegionId'])
    request.add_query_param('PhoneNumbers', params['PhoneNumbers'])
    request.add_query_param('SignName', params['SignName'])
    request.add_query_param('TemplateCode', params['TemplateCode'])
    request.add_query_param('TemplateParam', params['TemplateParam'])

    response = client.do_action(request)
    print(str(response, encoding='utf-8'))
    return code


# 验证用户输入的验证码是否正确
def verify_code(phone_number, user_input_code):
    r = redis.Redis(host=redis_host, port=redis_port, password=redis_password, db=Config.REDIS_DB)
    stored_code = r.get(phone_number)
    if stored_code and stored_code.decode('utf-8') == user_input_code:
        r.delete(phone_number)
        return True
    return False


if __name__ == '__main__':
    phone_number = '18077955824'
    code = send_sms_code(phone_number)
    print('验证码已发送，请查收。')

    user_input_code = input('请输入收到的验证码：')
    if verify_code(phone_number, user_input_code):
        print('验证码正确！')
    else:
        print('验证码错误！')
